package hit.reports;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

/**
 * A builder used to create an HTML copy of the report.
 *
 */
public class HTMLBuilder extends ReportBuilder {
	
	/**
	 * Prints the report to HTML, and saves it to the file provided
	 * @param toSave Where to save the new report.
	 * @return The location where the file was saved.
	 * @throws UnsupportedOperationException if the builder contains
	 * 	a {@link BuilderObject} not yet implemented.
	 * @throws IOException if there was a problem saving the file.
	 * @throws IllegalArgumentException if the file is equal to null.
	 */
	public File GetOutput(File toSave) throws IllegalArgumentException, 
			UnsupportedOperationException, IOException
	{
		if (toSave == null)
			throw new IllegalArgumentException();
		
		String result = "<html>\n<head>\n<title>" + this.getTitle() + "</title>\n</head>\n";
		result += "<body>\n";
		result += "<h1>" + this.getTitle() + "</h1>\n";
		
		Iterator<BuilderObject> iter = this.GetObjectsIterator();
		
		while (iter.hasNext())
		{
			BuilderObject temp = iter.next();
			
			if (temp instanceof BuilderHeader)
			{
				result += "<h2>" + ((BuilderHeader)temp).getValue() + "</h2>";
			}
			else if (temp instanceof BuilderParagraph)
			{
				String value = ((BuilderParagraph)temp).getValue();
				result += "<p>" + value.replaceAll("\n", "<br/>") + "</p>";
			}
			else if (temp instanceof BuilderTable)
			{
				BuilderTable table = (BuilderTable)temp;
				String tableResult = "<table border=\"1\">\n<tr>\n";
				
				Iterator<TableColumn> colIter = table.GetColumnIterator();
				while (colIter.hasNext())
				{
					TableColumn col = colIter.next();
					tableResult += "<th>" + col.getTitle() + "</th>\n";
				}
				tableResult += "</tr>\n";
				
				Iterator<TableRow> rowIter = table.GetRowIterator();
				while (rowIter.hasNext())
				{
					TableRow row = rowIter.next();
					tableResult += "<tr>\n";
					
					colIter = table.GetColumnIterator();
					while(colIter.hasNext())
					{
						TableColumn col = colIter.next();
						String cellValue = row.GetItemValue(col);
						
						if (cellValue == null || cellValue.equals(""))
							cellValue = "&nbsp;";
						
						tableResult += "<td>" + cellValue + "</td>\n";
					}
					
					tableResult += "</tr>\n";
				}
				
				tableResult += "</table>";
				
				result += tableResult;
			}
			else if (temp instanceof BuilderBreak)
			{
				result += "</br>\n";
			}
			else
			{
				throw new UnsupportedOperationException();
			}
			
			result += "\n";
		}
		
		result += "</body>\n</html>";
		
		FileWriter writer = new FileWriter(toSave);
		BufferedWriter out = new BufferedWriter(writer);
		out.write(result);
		
		out.close();
		
		return toSave;
	}
}
